const products = [
    { id: 1, name: '商品1', price: 10.00, image: 'images/images01', quantity: 0 },
    { id: 2, name: '商品2', price: 20.00, image: 'images/images02', quantity: 0 },
    { id: 3, name: '商品3', price: 110.00, image: 'images/images03', quantity: 0 },
    { id: 4, name: '商品4', price: 150.00, image: 'images/images04', quantity: 0 },
];

let cart = [...products];

const productsList = document.getElementById('products-list');
const selectAllBtn = document.getElementById('select-all');
const clearCartBtn = document.getElementById('clear-cart');
const checkoutBtn = document.getElementById('checkout');
const selectedCountEl = document.getElementById('selected-count');
const totalEl = document.getElementById('total');

document.addEventListener('DOMContentLoaded', () => {
    renderProducts();
    updateCartSummary();

    const savedCart = localStorage.getItem('cart');
    if (savedCart) {
        cart = JSON.parse(savedCart);
        renderProducts();
        updateCartSummary();
    }
});

function renderProducts() {
    productsList.innerHTML = '';

    if (cart.length === 0) {
        productsList.innerHTML = `
            <div class="cart-empty">
                <p>购物车是空的，快去选购商品吧！</p>
            </div>
        `;
        return;
    }

    cart.forEach(product => {
        const productEl = document.createElement('div');
        productEl.className = 'product';
        productEl.dataset.id = product.id;

        productEl.innerHTML = `
            <div class="product-checkbox">
                <input type="checkbox" id="product-${product.id}" class="product-select" >
            </div>
            <img src="${product.image}" alt="${product.name}" class="product-image">
            <div class="product-info">
                <h3 class="product-name">${product.name}</h3>
                <div class="product-price">¥${product.price.toFixed(2)}</div>
                <div class="product-quantity">
                    <button class="quantity-btn minus" data-id="${product.id}">-</button>
                    <input type="number" class="quantity-input" value="${product.quantity}" min="0" data-id="${product.id}">
                    <button class="quantity-btn plus" data-id="${product.id}">+</button>
                </div>
            </div>
            <div class="product-remove" data-id="${product.id}">
                <i class="fas fa-trash"></i>
            </div>
        `;

        productsList.appendChild(productEl);
    });

    updateSelectAllButtonState();
}

function updateCartSummary() {
    const selectedProducts = cart.filter(product => {
        const checkbox = document.getElementById(`product-${product.id}`);
        return checkbox ? checkbox.checked : false;
    });

    const selectedCount = selectedProducts.reduce((sum, product) => sum + product.quantity, 0);
    const total = selectedProducts.reduce((sum, product) => sum + (product.price * product.quantity), 0);

    selectedCountEl.textContent = selectedCount;
    totalEl.textContent = total.toFixed(2);

    localStorage.setItem('cart', JSON.stringify(cart));
}

function updateSelectAllButtonState() {
    if (cart.length === 0) {
        selectAllBtn.textContent = '全选';
        return;
    }
    const allChecked = cart.every(product => {
        const checkbox = document.getElementById(`product-${product.id}`);
        return checkbox && checkbox.checked;
    });
    selectAllBtn.textContent = allChecked ? '取消全选' : '全选';
}
document.addEventListener('click', (e) => {
    if (e.target.classList.contains('minus')) {
        const productId = parseInt(e.target.dataset.id);
        const input = document.querySelector(`.quantity-input[data-id="${productId}"]`);
        input.value = parseInt(input.value) - 1; 
        updateProductQuantity(productId, parseInt(input.value));
    }

    if (e.target.classList.contains('plus')) {
        const productId = parseInt(e.target.dataset.id);
        const input = document.querySelector(`.quantity-input[data-id="${productId}"]`);
        input.value = parseInt(input.value) + 1;
        updateProductQuantity(productId, parseInt(input.value));
    }

    if (e.target.classList.contains('fa-trash') || e.target.classList.contains('product-remove')) {
        const productId = parseInt(e.target.closest('.product-remove').dataset.id);
        removeFromCart(productId);
    }
});

document.addEventListener('change', (e) => {
    if (e.target.classList.contains('product-select')) {
        updateSelectAllButtonState();
        updateCartSummary();
    }

    if (e.target.classList.contains('quantity-input')) {
        const productId = parseInt(e.target.dataset.id);
        const quantity = parseInt(e.target.value) || 1;
        updateProductQuantity(productId, quantity);
    }
});

selectAllBtn.addEventListener('click', () => {
    const isSelectAll = selectAllBtn.textContent === '全选';
    
    cart.forEach(product => {
        const checkbox = document.getElementById(`product-${product.id}`);
        if (checkbox) {
            checkbox.checked = isSelectAll;}
    });
    
    updateSelectAllButtonState();
    updateCartSummary();
});

clearCartBtn.addEventListener('click', () => {
    cart = [];
    localStorage.removeItem('cart');
    renderProducts();
    updateCartSummary();
});

checkoutBtn.addEventListener('click', () => {
    const selectedProducts = cart.filter(product => {
        const checkbox = document.getElementById(`product-${product.id}`);
        return checkbox && checkbox.checked && product.quantity > 0;
    });

    if (selectedProducts.length === 0) {
        alert('请至少选择一件商品');
        return;
    }

    alert(`结算成功！共 ${selectedProducts.reduce((sum, p) => sum + p.quantity, 0)} 件商品，总价 ¥${selectedProducts.reduce((sum, p) => sum + (p.price * p.quantity), 0).toFixed(2)}`);

    cart = cart.filter(product => {
        const checkbox = document.getElementById(`product-${product.id}`);
        return !(checkbox && checkbox.checked);
    });

    localStorage.setItem('cart', JSON.stringify(cart));
    renderProducts();
    updateCartSummary();
});

function updateProductQuantity(productId, quantity) {
    const product = cart.find(p => p.id === productId);
    if (product) {
        product.quantity = quantity;
        updateCartSummary();
    }
}

function removeFromCart(productId) {
    const productEl = document.querySelector(`.product[data-id="${productId}"]`);
    if (productEl) {
        productEl.classList.add('fade-out');

        setTimeout(() => {
            cart = cart.filter(product => product.id !== productId);
            localStorage.setItem('cart', JSON.stringify(cart));
            renderProducts();
            updateCartSummary();
        }, 300);
    }
}